<template>
	<view class="container">
		<!-- 公共模块，显示返回箭头和标题 -->
		<public-module leftIcon="arrow-left" :title="title" />

		<!-- 用户信息卡片 -->
		<view class="user-info-card">
			<view class="info-item name-item text-center">
				<text class="info-value">{{ userNickname }}</text>
			</view>
			<view class="info-item score-rate-item">
				<view class="score-container">
					<text class="info-label">模考平均分</text>
					<text class="info-value score-value">{{ avgScore }}</text>
				</view>
				<view class="rate-container">
					<text class="info-label">平均击败率</text>
					<text class="info-value rate-value">{{ avgBeatRate }}%</text>
				</view>
			</view>
		</view>

		<!-- 模块正确率六边形图 -->
		<view class="module-radar-card">
			<view class="card-title">模块正确率(%)</view>
			<view class="radar-container flex-center">
				<view v-if="!radarLoaded" class="radar-loading">
					<text>加载中...</text>
				</view>
				<canvas v-else id="moduleRadarChart" canvas-id="moduleRadarChart" class="radar-chart"></canvas>
			</view>
		</view>

		<!-- 模块用时柱状图 -->
		<view class="module-time-card">
			<view class="card-title">模块用时(min)</view>
			<view class="time-container">
				<view v-if="!timeLoaded" class="time-loading">
					<text>加载中...</text>
				</view>
				<canvas v-else-if="!timeDataEmpty" id="moduleTimeChart" canvas-id="moduleTimeChart"
					class="time-chart"></canvas>
				<view v-else class="time-empty">
					<text>暂无模块用时数据</text>
				</view>
			</view>
		</view>

		<!-- 模考折线图 -->
		<view class="chart-container">
			<view class="chart-title">模考折线</view>
			<view v-if="!chartLoaded" class="chart-loading">
				<text>加载图表中...</text>
			</view>
			<view class="scroll-wrapper" v-else>
				<canvas id="examLineChart" canvas-id="examLineChart" class="chart" :ontouch="true" @touchstart="touchstart"
					@touchmove="touchmove" @touchend="touchend"></canvas>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		examReviewPersonal
	} from "@/config/api.js";
	// 修正uCharts引入路径
	import uCharts from '@/uni_modules/uview-ui/components/u-charts/u-charts.js';

	export default {
		data() {
			return {
				title: '模考雷达',
				userNickname: '',
				avgScore: 0,
				avgBeatRate: 0,
				avgPolitics: 0,
				avgCommonSense: 0,
				avgLanguage: 0,
				avgQuantity: 0,
				avgJudgment: 0,
				avgData: 0,
				avgPoliticsTime: 0,
				avgCommonSenseTime: 0,
				avgLanguageTime: 0,
				avgQuantityTime: 0,
				avgJudgmentTime: 0,
				avgDataTime: 0,
				examTimes: [],
				examScores: [],
				lineChart: null,
				radarChart: null,
				timeChart: null,
				currentId: null,
				chartLoaded: false,
				radarLoaded: false,
				timeLoaded: false,
				timeDataEmpty: false,
				windowWidth: 0,
				chartRendering: {
					line: false,
					radar: false,
					time: false
				},
				// 新增：存储 canvas 上下文
				radarContext: null,
				timeContext: null,
				lineContext: null,
				// 新增：uCharts实例
				uChartsInstance: {}
			};
		},
		methods: {
			initRadarChart() {
				if (this.chartRendering.radar) return;
				this.chartRendering.radar = true;

				// 获取 canvas 上下文
				try {
					this.radarContext = uni.createCanvasContext('moduleRadarChart', this);
				} catch (err) {
					console.error('获取雷达图 canvas 上下文失败', err);
					this.radarLoaded = true;
					return;
				}

				try {
					// 确保数据是有效的数值类型
					const radarData = [
						parseFloat(this.avgPolitics) || 0,
						parseFloat(this.avgCommonSense) || 0,
						parseFloat(this.avgLanguage) || 0,
						parseFloat(this.avgQuantity) || 0,
						parseFloat(this.avgJudgment) || 0,
						parseFloat(this.avgData) || 0
					];

					this.radarChart = new uCharts({
						$this: this,
						canvasId: 'moduleRadarChart',
						type: 'radar',
						fontSize: 10,
						legend: {
							show: false
						},
						categories: ['政治', '常识', '言语', '数量', '判断', '资料'],
						series: [{
							name: '模块正确率(%)',
							data: radarData,
							color: '#1890ff',
							areaOpacity: 0.3,
							symbol: 'circle',
							symbolSize: 4,
							// 显示数据点上的数值
							label: {
								show: true,
								fontSize: 10,
								color: '#333',
								// 自定义标签格式，显示百分比
								formatter: function(val) {
									return val + '%';
								}
							}
						}],
						width: this.windowWidth - 70,
						height: 300,
						// 传入 canvas 上下文
						context: this.radarContext,
						extra: {
							radar: {
								gridType: "circle",
								gridColor: "#CCCCCC",
								gridCount: 3,
								opacity: 1,
								max: 100,
								labelShow: true,
								linearType: "custom",
								border: false
							},
							animation: true,
							animationDuration: 1500, // 更长的动画持续时间
							animationEasing: 'easeOutCubic', // 缓动效果
							tooltip: {
								show: true,
								background: 'rgba(0,0,0,0.7)',
								color: '#fff',
								fontSize: 12,
								format: function(val, name) {
									return `${name}: ${val}%`;
								}
							}
						}
					});

					this.radarLoaded = true;
					console.log('雷达图初始化成功');
				} catch (error) {
					console.error('初始化雷达图失败:', error);
					this.radarLoaded = true;
				}
			},
			initTimeChart() {
				if (this.chartRendering.time) return;
				this.chartRendering.time = true;

				// 构建模块用时数据对象
				const timeData = [{
						name: '政治',
						value: parseFloat(this.avgPoliticsTime || 0)
					},
					{
						name: '常识',
						value: parseFloat(this.avgCommonSenseTime || 0)
					},
					{
						name: '言语',
						value: parseFloat(this.avgLanguageTime || 0)
					},
					{
						name: '数量',
						value: parseFloat(this.avgQuantityTime || 0)
					},
					{
						name: '判断',
						value: parseFloat(this.avgJudgmentTime || 0)
					},
					{
						name: '资料',
						value: parseFloat(this.avgDataTime || 0)
					}
				];

				// 检查是否所有时间数据都是0
				const allZero = timeData.every(item => item.value === 0);
				this.timeDataEmpty = allZero;

				if (allZero) {
					console.log('所有模块用时数据为0，显示空状态');
					this.timeLoaded = true;
					return;
				}

				// 获取 canvas 上下文
				try {
					this.timeContext = uni.createCanvasContext('moduleTimeChart', this);
				} catch (err) {
					console.error('获取柱状图 canvas 上下文失败', err);
					this.timeLoaded = true;
					return;
				}

				try {
					this.timeChart = new uCharts({
						$this: this,
						canvasId: 'moduleTimeChart',
						type: 'column',
						fontSize: 10,
						padding: [20, 10, 60, 10], // 增加底部padding，避免x轴标签被遮挡
						legend: {
							show: false
						},
						categories: timeData.map(item => item.name),
						series: [{
							name: '模块用时(min)',
							data: timeData.map(item => item.value),
							color: '#1890ff'
						}],
						xAxis: {
							disableGrid: true,
							show: true,
							fontSize: 9,
							rotateLabel: 30, // 旋转x轴标签，避免重叠
							itemCount: 6, // 显示所有6个模块
							gridColor: '#f0f0f0'
						},
						yAxis: {
							min: 0,
							max: Math.max(...timeData.map(item => item.value)) + 5 || 10,
							step: 5,
							labelCount: 5,
							width: 40,
							gridColor: '#f0f0f0',
							gridType: 'dashed'
						},
						width: this.windowWidth - 70,
						height: 300,
						// 传入 canvas 上下文
						context: this.timeContext,
						extra: {
							column: {
								width: 20, // 柱子宽度
								borderRadius: 5 // 柱子圆角
							},
							animation: true,
							animationDuration: 1000,
							tooltip: {
								show: true,
								background: 'rgba(0,0,0,0.7)',
								color: '#fff',
								fontSize: 12,
								format: function(val, name, category) {
									return `${category}: ${val.toFixed(1)}分钟`;
								}
							}
						}
					});

					this.timeLoaded = true;
					console.log('柱状图初始化成功');
				} catch (error) {
					console.error('初始化柱状图失败:', error);
					this.timeLoaded = true;
				}
			},
			initLineChart() {
				if (this.chartRendering.line) return;
				this.chartRendering.line = true;

				// 获取 canvas 上下文
				try {
					this.lineContext = uni.createCanvasContext('examLineChart', this);
				} catch (err) {
					console.error('获取折线图 canvas 上下文失败', err);
					this.chartLoaded = true;
					return;
				}

				// 确保examTimes和examScores是有效的数组
				if (!Array.isArray(this.examTimes) || this.examTimes.length === 0) {
					console.warn('examTimes 不是有效的数组或为空，使用默认数据');
					this.examTimes = ['暂无数据'];
					this.examScores = [0];
				}

				// 计算canvas宽度，确保支持滑动
				const baseWidth = this.windowWidth - 30; // 基础宽度
				const itemWidth = 30; // 每个数据点的宽度
				// 当数据点少于7个时，使用基础宽度；否则根据数据点数量计算宽度
				const chartWidth = this.examTimes.length <= 7 ? baseWidth : this.examTimes.length * itemWidth;
				// 确保图表宽度不会超出容器过多，添加右侧留白
				const finalWidth = Math.max(baseWidth, chartWidth);

				console.log('折线图配置信息:', {
					dataPoints: this.examTimes.length,
					baseWidth,
					chartWidth,
					finalWidth,
					windowWidth: this.windowWidth
				});

				try {
					this.lineChart = new uCharts({
						$this: this,
						canvasId: 'examLineChart',
						type: 'line',
						fontSize: 11,
						padding: [10, 45, 60, 0], // 增加右侧padding，确保最后一个数据点完全显示
						legend: {
							show: false,
						},
						categories: this.examTimes,
						series: [{
							name: '考试分数',
							data: this.examScores,
							color: '#1890ff',
							type: 'line',
							symbol: 'circle',
							symbolSize: 6,
							label: {
								show: false
							},
							lineStyle: {
								width: 2
							}
						}],
						xAxis: {
							disableGrid: true,
							show: true,
							fontSize: 10,
							rotateLabel: 90,
							scrollShow: true,
							scrollAlign: 'left',
							itemCount: Math.min(7, this.examTimes.length), // 动态设置显示的数据点数量
							scrollColor: "#A6A6A6", // 滚动条颜色
							scrollBackgroundColor: "#EFEBEF", // 滚动条背景颜色
							format: function(val, index) {
								if (val && val.length > 5) {
									return val.substring(0, 5);
								}
								return val;
							}
						},
						yAxis: {
							width: 30,
							gridColor: '#f0f0f0',
							gridType: 'dashed',
							data: [{
								min: 50, 
								max: 95,
								step: 5 // 每5分一个间隔
							}],
							decimal: 0,
							splitNumber: 9, // 设置合适的刻度数量
							// 添加背景色设置，确保滑动前后一致
							gridType: 'dashed',
							gridColor: '#f0f0f0',
							gridEval: 1
						},
						// 设置图表背景色为白色，避免滑动时出现黑色背景
						background: '#ffffff',
						width: finalWidth,
						height: 350,
						context: this.lineContext,
						// 启用滑动功能
						enableScroll: true,
						scrollAlign: 'left',
						touchMoveLimit: 24,
						extra: {
							line: {
								type: 'straight', // 使用直线连接点
								width: 2 // 线条宽度
							},
							tooltip: {
								show: true,
								background: 'rgba(0,0,0,0.7)',
								color: '#fff',
								fontSize: 12,
								format: function(val, item, category) {
									return `考试时间: ${category}\n分数: ${val}分`;
								}
							}
						}
					});

					this.uChartsInstance['examLineChart'] = this.lineChart;
					this.chartLoaded = true;
					console.log('折线图初始化成功，数据点数量:', this.examTimes.length, 'canvas宽度:', finalWidth);
				} catch (error) {
					console.error('初始化折线图失败:', error);
					this.chartLoaded = true;
				}
			},
			async loadData(userid) {
				try {
					const res = await examReviewPersonal(userid);
					if (res.code === 200) {
						const data = res.data[0];
						this.userNickname = data.user_nickname;
						this.avgScore = data.avg_score;
						this.avgBeatRate = data.avg_beat_rate;
						this.avgPolitics = data.avg_politics || 0;
						this.avgCommonSense = data.avg_common_sense || 0;
						this.avgLanguage = data.avg_language || 0;
						this.avgQuantity = data.avg_quantity || 0;
						this.avgJudgment = data.avg_judgment || 0;
						this.avgData = data.avg_data || 0;
						this.avgPoliticsTime = data.avg_politics_time || 0;
						this.avgCommonSenseTime = data.avg_common_sense_time || 0;
						this.avgLanguageTime = data.avg_language_time || 0;
						this.avgQuantityTime = data.avg_quantity_time || 0;
						this.avgJudgmentTime = data.avg_judgment_time || 0;
						this.avgDataTime = data.avg_data_time || 0;

						console.log('模块用时数据:', {
							politics: this.avgPoliticsTime,
							commonSense: this.avgCommonSenseTime,
							language: this.avgLanguageTime,
							quantity: this.avgQuantityTime,
							judgment: this.avgJudgmentTime,
							data: this.avgDataTime
						});

						// 转换考试时间和分数为数组
						this.examTimes = data.exam_times ? data.exam_times.split(',') : [];
						this.examScores = data.exam_scores ? data.exam_scores.split(',').map(score => parseFloat(
							score)) : [];

						// 格式化考试时间，只保留月日
						this.examTimes = this.examTimes.map(time => {
							const date = time.split(' ')[0];
							const [year, month, day] = date.split('-');
							return `${month}-${day}`;
						});

						this.$nextTick(() => {
							// 按照雷达图→柱状图→折线图的顺序初始化
							setTimeout(() => {
								this.initRadarChart();

								// 再初始化柱状图
								setTimeout(() => {
									this.initTimeChart();

									// 最后初始化折线图
									setTimeout(() => {
										this.initLineChart();
									}, 300);
								}, 300);
							}, 300);
						});
					} else {
						console.error('获取数据失败:', res.message);
						uni.showToast({
							title: res.message || '获取数据失败',
							icon: 'none'
						});
						this.chartLoaded = true;
						this.radarLoaded = true;
						this.timeLoaded = true;
					}
				} catch (error) {
					console.error('加载数据出错:', error);
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
					this.chartLoaded = true;
					this.radarLoaded = true;
					this.timeLoaded = true;
				}
			},
			// 新增：触摸事件处理函数
			touchstart(e) {
				console.log('touchstart event:', e);
				if (this.uChartsInstance[e.target.id]) {
					this.uChartsInstance[e.target.id].scrollStart(e);
				}
			},
			touchmove(e) {
				console.log('touchmove event:', e);
				if (this.uChartsInstance[e.target.id]) {
					// 阻止页面滚动，只允许图表滑动
					e.preventDefault();
					e.stopPropagation();
					this.uChartsInstance[e.target.id].scroll(e);
				}
			},
			touchend(e) {
				console.log('touchend event:', e);
				if (this.uChartsInstance[e.target.id]) {
					this.uChartsInstance[e.target.id].scrollEnd(e);
					this.uChartsInstance[e.target.id].touchLegend(e); // 启用图例交互
					this.uChartsInstance[e.target.id].showToolTip(e);
				}
			}
		},
		onLoad(options) {
			if (!options.userid) {
				uni.showToast({
					title: '无效的用户ID',
					icon: 'none'
				});
				return uni.navigateBack();
			}
			uni.getSystemInfo({
				success: (res) => {
					this.windowWidth = res.windowWidth;
				}
			});
			this.currentId = options.userid;
			this.loadData(options.userid);
		},
		onResize() {
			this.chartRendering = {
				line: false,
				radar: false,
				time: false
			};

			uni.getSystemInfo({
				success: (res) => {
					this.windowWidth = res.windowWidth;
					if (this.chartLoaded) {
						this.initLineChart();
					}
					if (this.radarLoaded) {
						this.initRadarChart();
					}
					if (this.timeLoaded && !this.timeDataEmpty) {
						this.initTimeChart();
					}
				}
			});
		}
	};
</script>

<style scoped>
	.container {
		background-color: #f8f8f8;
		min-height: 100vh;
	}

	.user-info-card {
		padding: 20px;
		background-color: #fff;
		border-radius: 10px;
		margin: 15px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
	}

	.info-item {
		margin-bottom: 15px;
	}

	.name-item {
		margin-bottom: 20px;
	}

	.score-rate-item {
		display: flex;
		justify-content: space-between;
		margin-bottom: 0;
	}

	.score-container,
	.rate-container {
		display: flex;
		align-items: center;
	}

	.info-label {
		font-size: 14px;
		color: #666;
		margin-right: 10px;
	}

	.info-value {
		font-size: 16px;
		font-weight: bold;
		color: #333;
	}

	.score-value {
		color: #1890ff;
	}

	.rate-value {
		color: #52c41a;
	}

	.module-radar-card,
	.module-time-card {
		padding: 15px;
		background-color: #fff;
		border-radius: 10px;
		margin: 15px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
	}

	.card-title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
		margin-bottom: 15px;
		margin-left: 10px;
	}

	.radar-container,
	.time-container {
		position: relative;
		padding: 0 10px;
		height: 300px;
		/* 确保容器有高度 */
	}

	.flex-center {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.radar-chart,
	.time-chart {
		width: 100%;
		height: 100%;
		/* 使用百分比确保继承容器高度 */
	}

	.radar-loading,
	.time-loading,
	.time-empty,
	.chart-loading {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
		color: #999;
	}

	.chart-container {
		padding: 15px;
		background-color: #fff;
		border-radius: 10px;
		margin: 15px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
	}

	.chart-title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
		margin-bottom: 15px;
		margin-left: 10px;
	}

	.text-center {
		text-align: center;
	}

	/* 为折线图添加滚动容器样式 */
	.scroll-wrapper {
		width: 100%;
		overflow-x: auto;
		overflow-y: hidden;
		/* 隐藏滚动条 */
		scrollbar-width: none; /* Firefox */
		-ms-overflow-style: none; /* IE 10+ */
		/* 添加平滑滚动效果 */
		scroll-behavior: smooth;
		/* 添加滑动指示器 */
		position: relative;
		/* 添加手势提示 */
		cursor: grab;
		/* 确保容器可以水平滚动 */
		white-space: nowrap;
	}
	
	.scroll-wrapper::-webkit-scrollbar {
		display: none; /* Chrome Safari */
	}
	
	/* 添加滑动提示 */
	.scroll-wrapper::after {
		content: "←→ 滑动查看";
		position: absolute;
		top: 10px;
		right: 10px;
		background: rgba(0, 0, 0, 0.6);
		color: white;
		font-size: 12px;
		padding: 4px 8px;
		border-radius: 4px;
		z-index: 10;
		opacity: 0.8;
		pointer-events: none;
		animation: fadeOut 2s forwards;
		animation-delay: 1s;
	}
	
	@keyframes fadeOut {
		0% { opacity: 0.8; }
		100% { opacity: 0; }
	}

	/* 确保canvas宽度可以超出容器，实现滑动效果 */
	.chart {
		width: auto;
		min-width: 100%;
		height: 350px;
		/* 添加过渡效果使渲染更平滑 */
		transition: all 0.3s ease;
		/* 防止图表内容被裁剪 */
		padding: 0 10px;
		box-sizing: border-box;
		/* 确保canvas可以水平滚动 */
		display: inline-block;
	}
</style>